// Handle datatable
App.directive('edGrid', ['$filter', 'Page', 'XCode', 'Auth', function ($filter, Page, XCode, Auth) {
    return {

        restrict: 'A',

        link: function (scope, elem, attrs) {

            var optionName = attrs.edGrid || 'grid';
            var dtOptions = scope[optionName];
            if (!dtOptions) {
                scope[optionName] = dtOptions = {};
            }

            var defaultOptButtons = [
                {
                    name: '编辑',
                    class: 'btn-edit',
                    icon: 'fa-edit',
                    auth: optionName + '.edit',
                    event: 'update'
                },
                {
                    name: '删除',
                    class: 'btn-delete',
                    icon: 'fa-trash-o',
                    auth: optionName + '.delete',
                    event: 'delete'
                }
            ]

            // 自定义列
            var columnDefs = {};
            if (typeof dtOptions.column_defs !== 'undefined') {
                for (var i = 0; i < dtOptions.column_defs.length; i++) {
                    columnDefs['column' + dtOptions.column_defs[i].target] = dtOptions.column_defs[i];
                }
            }

            var table;

            var options = {
                menus : [],
                serverSide: true,
                processing: false,
                paging: true,
                pageLength: 10,
                ordering: false,
                filter: false,
                ajax: function (data, callback, settings) {
                    var param = {};
                    // 添加绑定到query上的参数
                    for(var name in dtOptions.query) {
                        param[name] = dtOptions.query[name];
                    }
                    // 获取form表单数据
                    $('form[name="' + (attrs.edForm || optionName) + '"] [ng-model]').each(function(i, model) {
                        if ($(model).parents('[ed-combo],[ed-modal]').length == 0) {
                            var name = $(model).attr('name'), modelName = $(model).attr('ng-model');
                            param[name || AppUtil.getModelName(modelName)] = AppUtil.getModelValue(scope, modelName);
                        }
                    });
                    // 动态表格初始化参数
                    for(var name in dtOptions.extraParams) {
                        param[name] = dtOptions.extraParams[name];
                    }

                    if (options.paging) {
                    	param._pageIndex = data.start / data.length;
                        param._pageSize = data.length;
                    }

                    if (!dtOptions.lazy) {// 不是延迟加载
                        Page.ajaxGet(attrs.edUrl, param, function(resp) {
                            var rows = resp.data.rows;
                            if (!rows && angular.isArray(resp.data)) {// 工作流请求
                                rows = resp.data;
                            }
                            // 添加行号
                            $(rows).each(function(index, row) {
                                row._index = index + 1;
                            });
                            dtOptions.data = rows;
                            callback({recordsFiltered: resp.data.total, data: rows});
                        });
                    } else {
                        callback({recordsFiltered: 0, data: []});
                    }
                },
                dom: 'rt<"page-bar"<"col-md-5 col-sm-12 total-bar"li><"col-md-7 col-sm-12 pagination-bar"p>>',
                language: {
                    lengthMenu: '<select class="form-control input-sm"><option value="10">10</option><option value="20">20</option><option value="30">30</option><option value="40">40</option><option value="50">50</option></select>',
                    processing: "载入中",
                    recordsTotal: 'total',
                    paginate: {
                        previous: "<img src='./assets/admin/img/page-left.png'/>",
                        next: "<img src='./assets/admin/img/page-right.png'/>",
                        first: "第一页",
                        last: "最后一页"
                    },

                    zeroRecords: "没有数据",
                    info: "总共<span class='total'> _PAGES_ </span>页 <span class='total'> _TOTAL_ </span>条，显示第<span class='cur'> _START_ </span>到第 <span class='cur'> _END_  </span>条 ",
                    infoEmpty: "0条记录",
                    infoFiltered: ""
                }
            }

            // If dtOptions is defined in the controller, extend our default option.
            if (typeof dtOptions.options !== 'undefined') {
                angular.extend(options, dtOptions.options);
            }
            // If dtOptions is defined in the html, extend our default option.
            if (typeof attrs.options !== 'undefined') {
                angular.extend(options, AppUtil.jsonfy(attrs.options));
            }
            // 不需要分页
            if (!options.paging) {
                options.dom = 'rt';
            }
            // 是否延迟加载
            dtOptions.lazy = options.lazy === true;
            dtOptions.lazy = dtOptions.lazy || attrs.edLazy == 'true';// 增加ed-lazy，方便设置

            options.columns = [];

            var ths = [], thRowLenth = elem.find('thead tr').length;// 表头的行数
            var colsnum = [];

            elem.find('thead tr').each(function(rowIndex, tr) {
                $(tr).find('th').each(function(colIndex, th) {
                    if (rowIndex == thRowLenth - 1) {// 最后一行
                        if(thRowLenth==1) {
                            ths.push(th);
                        }
                    } else {
                        var rowspan = parseInt($(th).attr('rowspan') || '1');
                        if (rowspan + rowIndex == thRowLenth) {
                            ths.push(th);
                            colsnum.push([colIndex,0]);
                        }else {
                            var colArr = [colIndex,parseInt($(th).attr('colspan') || '1')];
                            colsnum.push(colArr);
                        }
                    }
                });
                if (rowIndex == thRowLenth - 1 && thRowLenth>1) {// 最后一行
                    var mcount = 0;
                    var beginindex = 0;
                    for(var index in colsnum) {
                        var count = colsnum[index];
                        if(beginindex==0) {
                            beginindex = count[0];
                        }
                        $(tr).find('th').each(function(colIndex, th) {
                            if(colIndex < count[1]+mcount && colIndex >= mcount) {
                                ths.splice(beginindex, 0, th);
                                beginindex++;
                            }
                            if(count[1]<1){
                                beginindex++;
                                return false;
                            }
                        });
                        mcount += count[1];
                    }
                }
            });
            // Get the thead rows.
            $(ths).each(function(index, th) {

                var columnDef = columnDefs['column' + index];

                var edData = $(th).attr('ed-data'), filters = [];
                if (edData && edData.indexOf('|') > 0) {// 指定了filter
                    filters = edData.split('|');
                    edData = filters.shift().trim();
                    $(th).attr('ed-data', edData);// 重新设置下，编辑时需要用

                    // 判断filter
                    if (filters.length > 0) {// 指定了过滤器
                        $(filters).each(function(i, filter) {
                            if (filter.indexOf(':') > 0) {// 存在参数，目前仅支持一个参数
                                var arr = filter.split(':');
                                var param = arr[1].trim();
                                if (param.substring(0, 1) == "'") {
                                    param = param.substring(1);
                                }
                                if (param.substring(param.length - 1) == "'") {
                                    param = param.substring(0, param.length - 1);
                                }
                                filters[i] = [arr[0].trim(), param];
                            } else {// 没有参数
                                filters[i] = [filter.trim()];
                            }
                            if (filters[i][0] == 'code') {// code表
                                $(th).attr('code', filters[i][1]);// 设置下拉选项，编辑时需要用
                            }
                        });
                    }
                }

                if (edData == '_checkbox') {// 多选框
                    scope[attrs.edModel + 's'] = [];// 避免判断是否undefined
                    $('<input type="checkbox" />').appendTo($(this)).click(function() {
                        var checkbox = $(this);
                        scope.$apply(function(){
                            dtOptions.selectAllRow(checkbox);
                        });
                    });
                    columnDef = {// 配置多选框模板
                        template: function(row){
                            return '<input type="checkbox" ed-click="selectRow" />'
                        }
                    };
                } else if (edData == '_edit') {// 默认操作列
                    if (typeof columnDef === 'undefined') {
                        columnDef = {
                            buttons: defaultOptButtons
                        };
                    } else {
                        columnDef = {
                            buttons: columnDef.buttons.concat(defaultOptButtons)
                        };
                    }
                } else if (edData == '_index') {
                    $(this).html('');
                }

                if (typeof columnDef !== 'undefined') {// 存在自定义列

                    if (typeof columnDef.template !== 'undefined') {// 指定了HTML模板
                        options.columns.push({
                            data: function (row) {
                                var template;
                                if (angular.isFunction(columnDef.template)) {// 通过function指定
                                    template = columnDef.template(row);
                                } else {
                                    template = columnDef.template;
                                }
                                // 判断权限
                                if (!Auth.validate($(template).attr('ed-auth'))) {
                                    template = $(template).removeAttr('ed-click').prop('outerHTML');
                                }
                                return template;
                            }
                        });
                    } else {// 按钮
                        var buttons = columnDef.buttons;
                        var template = '';
                        var ruleButtons = [];// 需要按照规则判断的按钮

                        for (var i = 0; i < buttons.length; i++) {
                            var button = buttons[i];
                            // 判断权限
                            if (!Auth.validate(button.auth)) {
                                continue;
                            }

                            var eventName = button.event;
                            if (typeof button.event !== 'string') {// 指定的function
                                eventName = 'event' + index + '_' + i;
                                dtOptions[eventName] = button.event;
                            } else if (button.event == 'update' && i > 0) {
                                // 加一个分隔线
                                template += '<div class="btn divider"></div>';
                            }
                            template += '<button class="btn btn-xs '+button.class+'" event="'+eventName+'"><i class="fa '+button.icon+'"></i> '+button.name+'</button>';
                            // 判断是否定义了enable和visiable
                            if (typeof button.enable == 'function' || typeof button.visiable == 'function') {
                                button.index = i;// 做个标记
                                ruleButtons.push(button);
                            }
                        }
                        options.columns.push({
                            data: function (row) {
                                if (ruleButtons.length == 0) {
                                    return template;
                                } else {// 定义了enable和visiable
                                    var div = $('<div>' + template + '</div>');
                                    var deleteButtons = [];// 不需要显示的button
                                    $(ruleButtons).each(function(index, button) {
                                        var btn = div.find('button:eq(' + button.index + ')');
                                        if (button.enable) {// 是否允许点击，默认可点击
                                            if (!button.enable(row)) {// 返回false
                                                btn.addClass('disabled');
                                            }
                                        }
                                        if (button.visiable) {// 是否显示，默认显示
                                            if (!button.visiable(row)) {// 返回false
                                                deleteButtons.push(btn);
                                            }
                                        }
                                    });
                                    if (deleteButtons.length > 0) {
                                        $(deleteButtons).each(function(index, btn) {
                                            btn.remove();
                                        });
                                    }
                                    return div.html();
                                }
                            }
                        });

                    }
                } else {// 不存在自定义列，都是通过th配置
                    options.columns.push({
                        data: function(row) {
                            var value = '';
                            if (typeof edData !== 'undefined') {
                                if (edData.indexOf('.') > 0) {
                                    var arr = edData.split('.');
                                    value = row[arr[0]] ? row[arr[0]][arr[1]] : "";
                                } else {
                                    value = row[edData];
                                }
                            }
                            if (typeof value == 'undefined') {
                                value = '';
                            }
                            if (filters.length > 0) {// 指定了过滤器
                                $(filters).each(function(i, filter) {
                                    value = filter.length == 1 ? $filter(filter[0])(value) : $filter(filter[0])(value, filter[1]);
                                });
                            }
                            return value;
                        }
                    });
                }
                // 设置固定宽度
                var edWidth = $(this).attr('ed-width');
                if (typeof edWidth !== 'undefined') {
                    options.columns[options.columns.length - 1].width = edWidth;
                } else if (index == 0 && (edData == '_index' || edData == '_checkbox')) {// 序号和多选框
                    options.columns[options.columns.length - 1].width = '25px';
                }
            });

            // Load the datatable!
            table = elem.DataTable(options)
                .on('draw.dt', function () {
                    var scope = elem.scope();

                    if (dtOptions.data.length > 0) {
                        // 添加行号，为了取值
                        elem.find('tbody tr').each(function(index, tr) {
                            $(tr).attr('_index', dtOptions.data[index]._index);
                        });
                        // 按钮
                        elem.find('tbody tr button[event]').unbind('click').bind('click', function () {
                            var button = $(this);
                            if (button.hasClass('disabled')) {
                                return;
                            }
                            scope.$apply(function(){
                                dtOptions[button.attr('event')](dtOptions.getRow(button), button);
                            });
                        } );

                        // 模板中的点击事件
                        elem.find('tbody tr td [ed-click]').unbind('click').bind('click', function () {
                            var clickEle = $(this);
                            scope.$apply(function(){
                                dtOptions[clickEle.attr('ed-click')](dtOptions.getRow(clickEle), clickEle);
                            });
                        } );

                        // 设置编辑属性
                        $(ths).each(function(index, th) {
                            th = $(th);
                            if (th.hasClass('edited')) {
                                $('table tr td:nth-child(' + (index + 1) + ')')
                                    .addClass(th.attr('class')).attr('ed-data', th.attr('ed-data')).attr('code', th.attr('code'));
                            }
                        });
                        elem.find('tbody tr td.edited').click(function() {
                            var td = $(this);
                            scope.$apply(function() {
                                dtOptions.editCel(td);
                            });
                        });
                    }

                    // 表格加载完成回调
                    if (typeof dtOptions.onDraw === 'function') {
                        dtOptions.onDraw(angular.copy(dtOptions.data));
                    }
                } );
            if (options.select) {// 设置了选择操作
                table.on('select', function (e, dt, type, indexes) {
                    if (options.select.onSelect) {
                        scope.$apply(function() {
                            options.select.onSelect(table.rows( { selected: true } ).data().toArray());
                        });
                    }
                } );
                //.on('deselect', function (e, dt, type, indexes) {
                //    if (options.select.onSelect) {
                //        scope.$apply(function() {
                //            options.select.onSelect(table.rows( { selected: true } ).data().toArray());
                //        });
                //    }
                //} );
            }

            // 获取行数据
            dtOptions.getRow = function(ele) {
                var row = dtOptions.data[$(ele).parents('tr:eq(0)').attr('_index') - 1];
                return angular.copy(row);
            }
            // 默认方法
            // 查询
            if (typeof dtOptions.query !== 'function') {
                dtOptions.query = function (params) {
                    //for (var key in params) {
                    //    dtOptions.query[key] = params[key];
                    //}
                    dtOptions.extraParams = params;
                    dtOptions.lazy = false;
                    table.draw();
                }
            }
            // reset
            if (typeof dtOptions.reset !== 'function') {
                dtOptions.reset = function () {
                    for (var name in dtOptions.query) {
                        delete dtOptions.query[name];
                    }
                }
            }
            // 新增
            if (typeof dtOptions.add !== 'function') {
                dtOptions.add = function () {
                    dtOptions.edit = true;
                    scope[attrs.edModel] = {
                        _add: true
                    };
                }
            }
            // 修改
            if (typeof dtOptions.update !== 'function') {
                dtOptions.update = function (row) {
                    dtOptions.edit = true;
                    scope[attrs.edModel] = row;
                }
            }
            // 删除
            if (typeof dtOptions.delete !== 'function') {
                dtOptions.delete = function (row) {
                    Page.confirm("确定要删除吗？", function () {
                        Page.ajaxPost(attrs.edModel + '/delete.do', row, function () {
                            dtOptions.query();
                        });
                    });
                }
            }
            // 保存
            if (typeof dtOptions.save !== 'function') {
                dtOptions.save = function () {
                    var model = attrs.edModel, data = scope[model];
                    Page.ajaxPost(data._add ? model + '/add.do' : model + '/update.do', data, function() {
                        dtOptions.cancel();
                        dtOptions.query();
                        scope[attrs.edModel] = {};
                    });
                }
            }

            // 取消
            if (typeof dtOptions.cancel !== 'function') {
                dtOptions.cancel = function () {
                    dtOptions.edit = false;
                    scope[attrs.edModel] = {};
                }
            }

            // 多选点击每行选择
            dtOptions.selectAllRow = function(checkbox) {
                elem.find('tbody tr td input[type="checkbox"]').prop("checked", checkbox.attr('checked') == 'checked');
                scope[attrs.edModel + 's'] = checkbox.attr('checked') == 'checked' ? dtOptions.data : [];
            }

            dtOptions.selectRow = function(row, ele) {
                var arr = [];
                elem.find('tbody tr td input[type="checkbox"]:checked').each(function() {
                    arr.push(dtOptions.getRow($(this)));
                });
                scope[attrs.edModel + 's'] = arr;
            }

            // 编辑单元格
            dtOptions.editCel = function(td) {
                td.on('keydown', function (event) {
                    var ntd = "";
                    if(event.keyCode=="40") {//下
                        var tr = $(td).parents().eq(0).next();
                        ntd = $(tr).find('td').eq(0);
                        while(!ntd.attr('ed-data') && ntd.next().get(0) && td.hasClass('editing')){
                            ntd = ntd.next();
                        }
                    }else if(event.keyCode=="38") {//上
                        var tr = $(td).parents().eq(0).prev();
                        ntd = $(tr).find('td').eq(0);
                        while(!ntd.attr('ed-data') && ntd.next().get(0) && td.hasClass('editing')){
                            ntd = ntd.next();
                        }
                    }else if(event.keyCode=="37") {//左
                        ntd = $(td).prev();
                        while(!ntd.attr('ed-data') && ntd.prev().get(0) && td.hasClass('editing')){
                            ntd = ntd.prev();
                        }
                    }else if(event.keyCode=="39" || event.keyCode=="9") {//右
                        ntd = $(td).next();
                        while(!ntd.attr('ed-data') && ntd.next().get(0) && td.hasClass('editing')){
                            ntd = ntd.next();
                        }
                    }
                    if(ntd && ntd.attr('ed-data')) {
                        dtOptions.editCel(ntd);
                    }
                });

                if (!td.hasClass('editing')) {
                    var name = td.attr('ed-data'), originalValue = dtOptions.getRow(td)[name], nowValue = td.attr('changed-data') || originalValue;
                    td.addClass('editing').empty();
                    var isSelect = false;// 是否为下拉菜单
                    var maxWidth = td.width();
                    if (typeof(td.attr("code")) != "undefined") {// 下拉选项
                        isSelect = true;
                        var html = '<select class="form-control" tabindex=1 name="' + name + '" style="max-width:' + maxWidth + 'px;"></option>';
                        $(XCode.getSelectOption(td.attr("code"))).each(function(index, option) {
                            html += '<option value="' + option.value + '"' + (nowValue == option.value ? ' selected="selected"' : '') + '>' + option.name + '</option>';
                        });
                        html += '</select>';
                        td.append(html);
                    } else {// 文本框
                        td.append('<input type="text" class="form-control tabindex=1 input-small" style="max-width:' + maxWidth + 'px;" value="' + nowValue + '">');
                    }
                    // 事情焦点重新设置值
                    if (isSelect) {// 下拉选择
                        td.find(':first-child').focus();
                    } else {// 文本框，设置光标
                        td.find(':first-child').val('').focus().val(nowValue);
                    }
                    // 失去焦点设置修改后的值
                    td.find(':first-child').blur(function() {
                        var value = $(this).val();
                        td.removeClass('editing').empty();
                        if (isSelect) {// 下拉选择
                            td.html($(this).find("option:selected").text());
                        } else {
                            td.html($(this).val());
                        }
                        if (originalValue == value || (!originalValue && value == '')) {// 和原始值一样
                            td.removeAttr('changed').removeClass('changed');
                        } else {// 修改了
                            td.attr('changed-data', value).addClass('changed');
                        }
                    });
                }
            }
            // 获取修改过的行
            dtOptions.getChangedRows = function() {
                var rows = [];
                elem.find('tbody tr').each(function(index, tr) {
                    var changedTds = $(tr).find('td.changed');
                    if (changedTds.length > 0) {// 修改过
                        var row = dtOptions.getRow(changedTds.get(0));
                        $(changedTds).each(function() {
                            row[$(this).attr('ed-data')] = $(this).attr('changed-data');
                        });
                        rows.push(row);
                    }
                });
                return rows;
            }
        }
    }
}]);

// Handle datatable dynamic
App.directive('edGridDynamic', ['$parse', 'Page', '$compile', function ($parse, Page, $compile) {

    return {

        restrict: 'A',

        controller: ['$scope', '$element', function ($scope, $element) {
            var optionName = $element.attr('ed-grid-dynamic') || 'grid';
            if (!$scope[optionName]) {
                $scope[optionName] = {};
            }

            $scope[optionName].setDynamicTable = function(url, params) {
                // 绑定查询条件
                $scope[optionName].extraParams = params;

                if (typeof url == 'string') {// 指定的是url
                    Page.ajaxGet(url, params, function(resp) {
                        initTable(resp.data)
                    });
                } else if (angular.isArray(url)) {// 指定的是json
                    initTable(url)
                }
            }

            function initTable(thRows) {
                var html = '<table ed-grid="' + optionName + '" class="table table-striped table-bordered table-advance table-hover"'
                    + '       ed-url="' + $element.attr('ed-url') + '" ed-model="' + $element.attr('ed-model') + '">'
                    + '    <thead><tr>';

                //var thRows = resp.data;
                if (angular.isArray(thRows) && thRows.length > 0) {
                    if (angular.isArray(thRows[0])) {// 多表头
                        $(thRows).each(function(rowIndex, row) {
                            $(row).each(function(colIndex, col) {
                                var menuEdit = '';
                                if(typeof(col.colspan) == "undefined" && typeof(col.edit) != "undefined") {//不添加右键菜单
                                    menuEdit = ' ed-menu="'+col.col+'" target="'+col.col+'" ng-init=\'model='+ angular.toJson($scope[optionName].menus)+'\'';
                                }
                                html += '<th' + (typeof(col.width) != "undefined" ? ' width="' + col.width + '"' : '') + (typeof(col.rowspan) != "undefined" ? ' rowspan="' + col.rowspan + '"' : '') + (typeof(col.colspan) != "undefined" ? ' colspan="' + col.colspan + '"' : '') +  (typeof(col.edit) != "undefined" ? ' class="edited ' + col.edit + '"' : '') + menuEdit + ' ed-data="' + col.col + (col.option ? ' | code : ' + col.option + '' : '') + '"' + '>' + col.name + '</th>'
                            });
                            if (rowIndex != thRows.length - 1) {
                                html += '</tr><tr>';
                            }
                        });
                    } else {// 单层表头
                        $(thRows).each(function(index, col) {
                            var menuEdit = '';
                            if(typeof(col.edit) != "undefined") {//不添加右键菜单
                                menuEdit = ' ed-menu="'+col.col+'" target="'+col.col+'" ng-init=\'model='+ angular.toJson($scope[optionName].menus)+'\'';
                            }
                            html += '<th' + (typeof(col.width) != "undefined" ? ' width="' + col.width + '"' : '') + (typeof(col.edit) != "undefined" ? ' class="edited ' + col.edit + '"' : '') + menuEdit +' ed-data="' + col.col + (col.option ? ' | code : ' + col.option + '' : '') + '"' + '>' + col.name + '</th>'
                        });
                    }
                }

                html += '</tr></thead></table>';

                $element.empty().append(html);
                $compile($element)($scope);
                //$element.empty().append($compile(html)($scope));
            }
        }],

        link: function (scope, elem, attrs) {

        }
    }
}]);